<template>
  <div class="box">
    <div class="menu-box">
      <img class="icon-menu" src="/image/detail/icon1.png" alt="" @click="backtop" />
      <img class="icon-menu" src="/image/detail/icon2.png" alt="" @click="showCollect" />
      <img class="icon-menu" src="/image/detail/icon3.png" alt="" @click="openChat" />
      <img class="icon-menu" src="/image/detail/icon4.png" alt="" @click="openInfo(1)" />
      <img class="icon-menu" src="/image/detail/icon5.png" alt="" @click="openInfo(2)" />
    </div>
    <div v-if="mailShow" class="email-box">
      {{ language.nav.Email }} : {{ store.footerData.email }}
    </div>
    <div v-if="mobileShow" class="mobile-box">{{ store.footerData.phone }} （ 09:00-21:00 ）</div>
    <div v-if="chatShow" class="chat-box">
      <div class="chat-box-header">
        <img class="c-logo" src="/image/common/circle-logo.png" alt="" />
        <div>
          <div class="c-name">{{ language.nav.company }}</div>
          <div class="c-text">{{ language.nav.ServiceHotline }}</div>
        </div>
        <img class="c-icon" src="/image/common/close2.png" alt="" @click="closeChat" />
      </div>
      <div class="chat-main-box">
        <div class="c-left">
          <div class="c-cont-box" ref="chatBox">
            <div class="c-cont-item" v-for="(item, index) in messageList" :key="index">
              <div class="cont-left" v-if="item.senderType == 2">
                <div v-if="item.contentType == 1" class="cont-right-text">{{ item.content }}</div>
                <div v-if="item.contentType == 2" class="cont-right-text">
                  <a-image :width="200" :src="item.content" />
                </div>
                <div v-if="item.contentType == 10 && !item.content.split('&&')[1]" class="cont-right-info">
                  <img class="cont-img" :src="JSON.parse(item.content)?.picUrl" alt="" />
                  <div v-if="JSON.parse(item.content)?.spuName">
                    <div class="cont-name">{{ JSON.parse(item.content)?.spuName }}</div>
                    <div class="cont-info" >
                      {{ nav.Prices }}:{{ store.currency }}{{ roundFractional((parseInt(JSON.parse(item.content)?.price) || 0) / 100, 2) }}/m
                    </div>
                  </div>
                </div>
              </div>
              <div class="cont-right" v-if="item.senderType == 1">
                <div></div>
                <div v-if="item.contentType == 1" class="cont-right-text">{{ item.content }}</div>
                <div v-if="item.contentType == 2" class="cont-right-text">
                  <a-image :width="200" :src="item.content" />
                </div>
                <div v-if="item.contentType == 10 && !item.content.split('&&')[1]" class="cont-right-info">
                  <img class="cont-img" :src="JSON.parse(item.content)?.picUrl" alt="" />
                  <div v-if="JSON.parse(item.content)?.spuName">
                    <div class="cont-name">{{ JSON.parse(item.content)?.spuName }}</div>
                    <div class="cont-info" >
                      {{ nav.Prices }}:{{ store.currency }}{{ roundFractional((parseInt(JSON.parse(item.content)?.price) || 0) / 100, 2) }}/m
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="c-bottom">
            <div class="btn-box">
              <div class="btn" @click="openCollect">{{ language.nav.ProductIntroduction }}</div>
              <a-upload
                name="file"
                :show-upload-list="false"
                :action="`${conf.baseURL}/app-api/infra/file/upload`"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <div class="upload-pic">
                  <loading-outlined v-if="loading"></loading-outlined>
                  <PictureOutlined v-else />
                </div>
              </a-upload>
            </div>
            <textarea class="text-area" v-model="messageInfo"></textarea>
            <div class="send-btn" @click="sendMessage">{{ language.nav.send }}</div>
          </div>
        </div>
        <div v-if="collectShow" class="c-right">
          <div class="header">{{ nav.mCollect }}({{ collectList.length }})</div>
          <div class="collect-main">
            <div
              v-for="(item, index) in collectList"
              :key="index"
              class="collect-box"
              @click="sendPro(item)"
            >
              <div class="c-imgs">
                <img :src="item.picUrl" alt="" />
              </div>
              <div>
                <div class="c-name">{{ item.spuName }}</div>
                <!-- <div class="c-info">克重:{{ item.weight }} | 幅宽:{{ item.width }}</div> -->
                <div class="c-info">
                  {{ nav.Prices }}:{{ store.currency
                  }}{{ roundFractional((item.price || 0) / 100, 2) }}/m
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="collectComp" class="collect-com">
      <collectBox :collectList="collectList" @delCollect="delCollect" @mouseleave="closeCollect" />
    </div>
    <a-modal
      width="300px"
      v-model:open="poupShow"
      :title="nav.delMess"
      :ok-text="nav.yes"
      :cancel-text="nav.no"
      :closable="false"
      @ok="delSure"
    ></a-modal>
  </div>
</template>

<script lang="ts" setup>
import conf, { language } from "~/conf";
import collectBox from "./collectBox.vue";
import { loginStore, commonStore } from "@/components/store";
import type { UploadChangeParam, UploadProps } from "ant-design-vue";

let poupShow = ref(false);
const store = commonStore();
const loginStores = loginStore();
const { nav, mess } = language;
let chatShow = ref(false);
type Tmess = {
  senderType: number;
  time: number;
  contentType: number;
  content: string;
};

const getList = async (isFirst?: boolean) => {
  const { data } = (await useServerFetch<{
    list: Tmess[];
    total: number;
  }>("/app-api/promotion/kefu-message/page", {
    method: "get",
    query: {
      sequence: 1,
      size: 100,
    },
  })) as {
    data: {
      list: Tmess[];
      total: number;
    };
  };
  if (data?.list) {
    messageList.value = data.list.reverse();
  }
  if (isFirst) {
    setTimeout(() => {
      if (chatBox.value) {
        chatBox.value.scrollTop = chatBox.value.scrollHeight;
      }
    }, 500);
  }
};
let messageList = ref<Tmess[]>([]);
type Tcollect = {
  picUrl: string;
  price: number;
  spuId: number;
  spuName: string;
  id: number;
};
let collectList = ref<Tcollect[]>([]);
let collectShow = ref(false);
let collectComp = ref(false);
let mailShow = ref(false);
let mobileShow = ref(false);
const loading = ref(false);
let cancelIdleCallback = ref(0); //取消收藏的id
let messageInfo = ref("");
const chatBox = ref<{
  scrollTop: number;
  scrollHeight: number;
}>({
  scrollTop: 0,
  scrollHeight: 0,
});
let timer: string | number | NodeJS.Timeout | null | undefined = null;
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    msgPush({
      contentType: 2,
      content: info.file.response.data,
      senderType: 1,
      time: new Date().getTime(),
    });
    loading.value = false;
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};

const beforeUpload = (file: UploadProps["fileList"][number]) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error(mess.uploadMessType);
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error(mess.uploadSize);
  }

  return isJpgOrPng && isLt5M;
};
const openChat = () => {
  if (!localStorage.getItem("userData")) {
    return (loginStores.needPoup = true);
  }
  chatShow.value = !chatShow.value;
  if (chatShow.value) {
    clearInterval(timer as any);
    timer = null;
    getList(true);
    timer = setInterval(() => {
      getList();
    }, 3000);
  } else {
    clearInterval(timer as any);
    timer = null;
  }
};
const closeChat = () => {
  chatShow.value = false;
  clearInterval(timer as any);
  timer = null;
};
const openCollect = () => {
  if (!localStorage.getItem("userData")) {
    return (loginStores.needPoup = true);
  }
  init(1);
  collectShow.value = !collectShow.value;
};
const sendMessage = async () => {
  msgPush({
    contentType: 1,
    content: messageInfo.value,
    senderType: 1,
    time: new Date().getTime(),
  });
  messageInfo.value = "";
};
const msgPush = (item: {
  senderType: number;
  time: number;
  contentType: number;
  content: string;
}) => {
  useServerFetch<{
    list: Tcollect[];
  }>("/app-api/promotion/kefu-message/send", {
    method: "post",
    body: item,
  });
  messageList.value.push(item);
  setTimeout(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }
  }, 200);
};
const sendPro = async (item: Tcollect) => {
  msgPush({
    senderType: 1,
    time: new Date().getTime(),
    content: JSON.stringify(item),
    contentType: 10,
  });
  setTimeout(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }
  }, 200);
};
const backtop = () => {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};
const showCollect = () => {
  if (!localStorage.getItem("userData")) {
    return (loginStores.needPoup = true);
  }
  init(2);
};
const openInfo = (index: number) => {
  if (index === 1) {
    mailShow.value = !mailShow.value;
  } else {
    mobileShow.value = !mobileShow.value;
  }
};
const init = async (type: number) => {
  //type 1 不需要显示弹窗 2 需要显示弹窗
  const { data, code } = await useServerFetch<{
    list: Tcollect[];
  }>("/app-api/product/favorite/page", {
    method: "post",
    body: {
      pageNo: 1,
      pageSize: 100,
    },
  });
  if (code === 0) {
    if (data.list) {
      collectList.value = data.list;
    }
    if (type === 2) {
      collectComp.value = !collectComp.value;
    }
  }
};
const delCollect = (id: number) => {
  cancelIdleCallback.value = id;
  poupShow.value = true;
};
const closeCollect = () => {
  collectComp.value = false;
};
const delSure = async () => {
  const { code, msg } = await useServerFetch("/app-api/product/favorite/delete", {
    method: "delete",
    body: {
      spuId: cancelIdleCallback.value,
    },
  });
  if (code === 0) {
    message.success(mess.saveSucess);
    let list = collectList.value.filter((item) => item.spuId != cancelIdleCallback.value);
    collectList.value = list;
  } else {
    message.error(msg);
    if (code == 401) {
      loginStores.needPoup = true;
    }
  }
};

defineExpose({
  init,
});
</script>

<style lang="stylus" scoped>
.box{
  position fixed
  right 13px
  bottom 43px
  z-index 99
  .collect-com{
    position absolute;
    right 60px
    bottom 20px
  }
  .menu-box{
    position absolute;
    right 0
    bottom 20px
    .icon-menu{
      width 42px;
      margin-bottom:8px
      cursor pointer
      display block
    }
  }
  .mobile-box{
    position absolute
    right 52px;
    bottom 30px;
    width: 250px;
    height: 36px;
    line-height:36px
    text-align:center
    background: #FFFFFF;
    border-radius: 6px;
    border: 2px solid #FFFFFF;
    box-shadow: 0px 1px 6px 2px rgba(102,102,102,0.24);
  }
  .email-box{
    position absolute
    right 52px;
    bottom 80px;
    width: 216px;
    height: 36px;
    line-height:36px
    text-align:center
    background: #FFFFFF;
    border-radius: 6px;
    border: 2px solid #FFFFFF;
    box-shadow: 0px 1px 6px 2px rgba(102,102,102,0.24);
  }

  .chat-box{
    position absolute
    right 52px;
    bottom 0;
    width: 670px;
    height: 670px;
    background: #FBFDFF;
    box-shadow: 0px 1px 6px 2px rgba(102,102,102,0.24);
    border-radius: 14px;
    border: 2px solid #FFFFFF;
    box-sizing border-box;
    .chat-box-header{
      position relative;
      width: 100%;
      height 74px;
      background: #44484C;
      border-radius: 14px 14px 0px 0px;
      padding 16px 24px;
      box-sizing border-box;
      display flex;
      justify-content flex-start;
      align-items flex-start;
      .c-logo{
        width: 42px;
        margin-right 17px
      }
      .c-icon{
        position absolute;
        right 13px
        top 20px
        width 18px
        cursor pointer
      }
      .c-name{
        font-weight: 300;
        font-size: 22px;
        color: #FFFFFF;
      }
      .c-text{
        font-size: 14px;
        color: #FFFFFF;
      }
    }
    .chat-main-box{
      display flex
      justify-content flex-start
      align-items flex-start
      .c-left{
        width 100%
        min-width 425px
        .c-cont-box{
          height 447px
          padding-bottom 20px
          box-sizing border-box
          overflow-y scroll
          .c-cont-item{
            .cont-img{
              width 60px
              margin-right:10px
              border-radius: 8px;
            }
            .cont-left{
              display inline-block
              margin-left:19px
              margin-top 20px;
              background: #EAEFEF;
              border-radius: 14px;
              padding 12px
              font-weight: 400;
              font-size: 16px;
              color: #333333;
              .cont-right-info{
                display flex
                justify-content flex-start;
                align-items center;
                margin-right:19px
                border-radius: 14px;
                .cont-name{
                  font-weight: 400;
                  font-size: 14px;
                }
                .cont-info{
                  font-weight: 400;
                  font-size: 12px;
                }
              }
            }
            .cont-right{
              display flex
              justify-content space-between;
              align-items center;
              .cont-right-text{
                display inline-block
                margin-right:19px
                margin-top 20px;
                background: #333333;
                border-radius: 14px;
                padding 12px
                font-weight: 400;
                font-size: 16px;
                color: #FFFFFF;
              }
              .cont-right-info{
                display flex
                justify-content flex-start;
                align-items center;
                margin-right:19px
                margin-top 20px;
                background: #333333;
                border-radius: 14px;
                padding 12px
                .cont-name{
                  font-weight: 400;
                  font-size: 14px;
                  color: #FFFFFF;
                }
                .cont-info{
                  font-weight: 400;
                  font-size: 12px;
                  color: #FFFFFF;
                }
              }
            }
          }
        }
        .c-bottom{
          position relative
          height: 147px;
          background: #FFFFFF;
          border-radius: 0px 0px 14px 14px;
          border-top: 2px solid #EAEFEF;
          box-sizing border-box;
          padding 10px 10px 22px
          .btn-box{
            display flex;
            justify-content flex-start;
            align-items center;
            .btn{
              height: 30px;
              line-height: 30px;
              padding 0 13px
              background: #FFFFFF;
              border-radius: 15px;
              border: 1px solid #333333;
              cursor pointer
            }
            .upload-pic{
              height: 30px;
              padding 0 12px
              background: #FFFFFF;
              border-radius: 15px;
              border: 1px solid #333333;
              cursor pointer
              display flex
              align-items center
              justify-content center
              margin-left 10px
            }
          }
          .text-area{
            display inline-block
            width 100%!important;
            height:45px!important;
            margin-top 10px
            border 0;
            resize none
          }
          .text-area:focus{
            outline: none;
          }
          .send-btn{
            position absolute
            right 10px
            bottom 10px
            width: 62px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            background: #333333;
            border-radius: 15px;
            border: 1px solid #333333;
            font-weight: 400;
            font-size: 14px;
            color: #FCFBFB;
            cursor pointer
          }
        }
      }
      .c-right{
        width: 248px;
        height:596px;
        border-radius: 0px 14px 14px 0px;
        border-left: 2px solid #EAEFEF;
        .header{
          height 33px
          line-height 33px
          border-bottom 1px solid #efefef
          padding-left 15px
        }

        .collect-main{
          height 545px;
          overflow-y auto;
          overflow-x hidden
          padding-left 5px;
          box-sizing:border-box
        }
        .collect-box{
          display flex;
          justify-content flex-start;
          align-items center;
          width: 233px;
          height: 71px;
          background: #fff;
          border-radius: 8px;
          padding 5px 7px;
          box-sizing border-box;
          margin-top 10px
          transition all .3s
          cursor pointer
          .c-imgs{
            width 60px
            height 60px
            border-radius: 8px;
            display flex
            justify-content center
            overflow hidden
            margin-right:8px
            img{
              width 100%
            }
          }
          .c-name{
            font-weight: 400;
            font-size: 14px;
            color: #333333;
            margin-bottom 7px
          }
          .c-info{
            font-weight: 400;
            font-size: 12px;
            color: #666666;
          }
        }
        .collect-box:hover{
          background: #F8F8F8;
        }
      }
      .text-area::-webkit-scrollbar {
          position absolute;
          right:4px
          width: 4px;
          height: 4px;
      }
      .text-area::-webkit-scrollbar-thumb {
          border-radius: 10px;
          background: #666666;
      }
      .text-area::-webkit-scrollbar-track {
          border-radius: 0;
          background: #fff;
      }
      .c-cont-box::-webkit-scrollbar {
          position absolute;
          right:4px
          width: 4px;
          height: 4px;
      }
      .c-cont-box::-webkit-scrollbar-thumb {
          border-radius: 10px;
          background: #666666;
      }
      .c-cont-box::-webkit-scrollbar-track {
          border-radius: 0;
          background: #fff;
      }

      .collect-main::-webkit-scrollbar {
          position absolute;
          right:4px
          width: 4px;
          height: 4px;
      }
      .collect-main::-webkit-scrollbar-thumb {
          border-radius: 10px;
          background: #666666;
      }
      .collect-main::-webkit-scrollbar-track {
          border-radius: 0;
          background: #fff;
      }
    }
  }
}
</style>
